package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    /**
     * 缓存查询所有商铺类型
     * @return 商铺类型列表
     */
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryTypeList() {
        //1.从redis缓存中查询商铺类型
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_TYPE_KEY);
        //2.判断缓存是否命中
        if(shopJson != null){
            //3.命中返回商铺信息List<ShopType> shopTypeList = JSONUtil.toList(JSONUtil.parseArray(shopJson), ShopType.class)
            //将字符串转为集合对象
            List<ShopType> shopTypeList = JSONUtil.toList(shopJson, ShopType.class);
            return Result.ok(shopTypeList);
        }
        //4.未命中，查询数据库所有商铺类型集合
        List<ShopType> shopTypeList = query().orderByAsc("sort").list();
        //5.数据库不存在，返回错误
        if(shopTypeList == null){
            return Result.fail("404");
        }
        //6.数据库存在，将集合对象转为字符串，写入redis缓存
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_TYPE_KEY,JSONUtil.toJsonStr(shopTypeList));
        return Result.ok(shopTypeList);
    }
}
